// pages/register/register.js
var app = getApp();
var util = require('../../utils/util');
var interval = null //倒计时函数
Page({

    /**
     * 页面的初始数据
     */
	data: {
		goods_image: "",
		username: "",
		time: '获取验证码', //倒计时 
		currentTime: 60, //限制60s
		isClick: false, //获取验证码按钮，默认允许点击
		uploadControls: {
			store_header: {
				name: "上传照片",
				image: "/images/updat.png",
				tag: "store_header"
			},
			business_images: {
				name: "上传照片",
				image: "/images/updat.png",
				tag: "business_images"
			},
			card_pros: {
				name: "上传照片",
				image: "/images/updat.png",
				tag: "card_pros"
			},
			card_cons: {
				name: "上传照片",
				image: "/images/updat.png",
				tag: "card_cons",
			},
			food_ok_image: {
				name: "上传照片",
				image: "/images/updat.png",
				tag: "food_ok_image"
			}
		},
		allImg: {},
		address: "",
		ischecked: false,
	    region:[]

	},

    /**
     * 生命周期函数--监听页面加载
     */
	onLoad: function (options) {
		// console.log(options,"kjsdfklsdajfklsajfkl商户用户ID");
		//用来判断是不是重新注册
		if (options.id != undefined){
			this.setData({
				id: options.id
			})
		}
		
		if (options.q != undefined) {
			let q = util.getJson(decodeURIComponent(options.q));
			console.log(q, "klsdjflksjfkl");
			this.setData({
				inv_id: q.inv_id
			})
			console.log(this.data.inv_id, "111111111111111")
		}
		this.getClassList();
	},
	//省市区选择器
	bindRegionChange: function (e) {
		console.log('picker发送选择改变，携带值为', e.detail.value)
		this.setData({
			region: e.detail.value
		})
	},
	//获取用户地理位置权限
	addresTap: function () {
		var that = this;
		wx.chooseLocation({
			success: function (res) {

				that.setData({
					address: res //调用成功直接设置地址
				})
			},
			fail: function () {
				wx.getSetting({
					success: function (res) {
						var statu = res.authSetting;
						if (!statu['scope.userLocation']) {
							wx.showModal({
								title: '是否授权当前位置',
								content: '需要获取您的地理位置，请确认授权，否则地图功能将无法使用',
								success: function (tip) {
									if (tip.confirm) {
										wx.openSetting({
											success: function (data) {
												if (data.authSetting["scope.userLocation"] === true) {
													wx.showToast({
														title: '授权成功',
														icon: 'success',
														duration: 1000
													})
													//授权成功之后，再调用chooseLocation选择地方
													wx.chooseLocation({
														success: function (res) {
															that.setData({
																address: res
															})
														},
													})
												} else {
													wx.showToast({
														title: '授权失败',
														icon: 'success',
														duration: 1000
													})
												}
											}
										})
									}
								}
							})
						}
					},
					fail: function (res) {
						wx.showToast({
							title: '调用授权窗口失败',
							icon: 'success',
							duration: 1000
						})
					}
				})
			}
		})
	},

	//单选按钮
	pwdChecked: function (e) {
		this.data.ischecked = !this.data.ischecked;
		this.setData({
			ischecked: this.data.ischecked
		})
		//   console.log(this.data.username, password);
	},
    /**
     * 用户手机号
     * */
	usernameInput: function (event) {
		// console.log("username==",event.detail.value)
		this.setData({
			username: event.detail.value
		})
	},
    /**
     * 获取验证码
     */
	gainAuthCodeAction: function () {
		let that = this;
		/*第一步：验证手机号码*/
		var myreg = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1})|(17[0-9]{1}))+\d{8})$/; // 判断手机号码的正则
		if (that.data.username.length == 0) {
			util.showSuccess('手机号码不能为空', 'none', false, 800);
			return;
		}

		if (that.data.username.length < 11) {
			util.showSuccess('手机号码长度有误！', 'none', false, 800);
			return;
		}

		if (!myreg.test(that.data.username)) {
			util.showSuccess('错误的手机号码！', 'none', false, 800);
			return;
		}
		/*第二步：设置计时器*/
		// 先禁止获取验证码按钮的点击
		that.setData({
			isClick: true,
		})
		// 60s倒计时 setInterval功能用于循环，常常用于播放动画，或者时间显示
		var currentTime = that.data.currentTime;
		interval = setInterval(function () {
			currentTime--; //减
			that.setData({
				time: currentTime + '秒后获取'
			})
			if (currentTime <= 0) {
				clearInterval(interval)
				that.setData({
					time: '获取验证码',
					currentTime: 60,
					isClick: false
				})
			}
		}, 1000);
		/*第三步：请求验证码接口，并记录服务器返回的验证码用于判断，这里服务器也可能不返回验证码，那验证码的判断交给后台*/
		// wx.request({})
		var apiUrl = '/api/v1/common/identifying_code';
		var apiData = {
			phone: that.data.username
		}
		util.fetchPost(apiUrl, apiData, function (res) {
			util.hideLoading();
			if (res.state == 1) {

			} else {
				util.message(res.datas);
			}
		});
	},

	//图片上传
	onFilePathTap: function (e) {
		var that = this;
		var tag = e.currentTarget.dataset.tag;
		util.showLoading();
		wx.chooseImage({
			count: 1,
			success(res) {
				const tempFilePaths = res.tempFilePaths
				wx.uploadFile({
					url: app.globalData.http_url + '/api/v1/common/upload',
					header: {
						'Content-Type': 'multipart/form-data'
					},
					filePath: tempFilePaths[0],
					name: 'file',
					formData: {
						key: app.globalData.key
					},
					success: function (result) {
						util.hideLoading();
						var res = JSON.parse(result.data);
						if (res.code != 1) {
							wx.showToast({
								title: '上传失败',
								icon: 'none'
							});
							return false;
						}
						console.log(res)
						console.log(tag)
						var allImg = that.data.allImg;
						switch (tag) {
							case "store_header":
								allImg["store_header"] = {
									id: res.id,
									path: res.path
								}
								break;
							case "business_images":
								allImg["business_images"] = {
									id: res.id,
									path: res.path
								};
								break;
							case "card_pros":
								allImg["card_pros"] = {
									id: res.id,
									path: res.path
								};
								break;
							case "card_cons":
								allImg["card_cons"] = {
									id: res.id,
									path: res.path
								};
								break;
							case "food_ok_image":
								allImg["food_ok_image"] = {
									id: res.id,
									path: res.path
								};
								break;
						}
						that.setData({
							allImg: allImg
						})
						console.log(that.data.allImg)

					},
					fail: function (res) {
						utils.hideLoading();
						utils.message('上传服务器上传失败,请稍后再试');
						console.log(res);
					}
				})
			}
		})
	},
	//删除照片
	onCloseImgTap: function (e) {
		var that = this;
		var tag = e.currentTarget.dataset.tag;
		var allImg = that.data.allImg;
		//	console.log(tag == allImg[tag],tag,allImg[tag])
		delete allImg[tag]
		that.setData({
			allImg: allImg
		})
		console.log(that.data.allImg)
	},
	//打印机种类
	getClassList: function () {
		var that = this;
		util.showLoading();
		util.fetchPost("/api/v1/common/print_list", {}, function (res) {
			if (res.state == 1) {
				var array = [];
				for (var i in res.datas) {
					array.push(res.datas[i].name)
				}
				that.setData({
					array: array,
					index: 0,
					classlist: res.datas,
				})
			} else {
				util.message(res.datas)
			}
		})
		util.hideLoading();
	},
	//选择打印机种类
	bindPickerChange: function (e) {
		this.setData({
			index: e.detail.value,
		});
	},
	//提交
	formSubmit: function (e) {
		console.log(e);
		var that = this;
		var name = e.detail.value.name;
		var username = e.detail.value.username;
		var schoolname = e.detail.value.schoolname;
		var code = e.detail.value.code;
		var allImg = that.data.allImg;
		console.log(that.data.region.length)

		if (name == "") {
			util.showSuccess('请输入姓名', 'none', false, 800);
			return false;
		}
		var myreg = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1})|(17[0-9]{1}))+\d{8})$/; // 判断手机号码的正则
		if (username.length == 0) {
			util.showSuccess('手机号码不能为空', 'none', false, 800);
			return;
		}

		if (username.length < 11) {
			util.showSuccess('手机号码长度有误！', 'none', false, 800);
			return;
		}

		if (!myreg.test(username)) {
			util.showSuccess('错误的手机号码！', 'none', false, 800);
			return;
		}
		if (code == "") {
			util.showSuccess('请输入验证码', 'none', false, 800);
			return false;
		}
		if (that.data.region.length==0){
			util.showSuccess('请选择地区', 'none', false, 800);
			return false;
		}
		if (schoolname==""){
			util.showSuccess('请输入学校名称', 'none', false, 800);
			return false;
		}
		if (allImg.store_header == undefined) {
			util.showSuccess('请上传学生证', 'none', false, 800);
			return false;
		}
		if (that.data.ischecked == false) {
			util.showSuccess('请同意 《用户协议及隐私政策》', 'none', false, 800);
			return false;
		}
		util.showLoading();
	
		wx.login({
			success(res) {
				if (that.data.id){
					var apiUrl = '/api/dis/login/again_register';
					var apiData = {
						name: name,
						username: username,
						code: code,
						js_code: res.code,
						image: allImg.store_header.id,
						area: that.data.region,
						school: schoolname,
						id: that.data.id
					}
				}else{
					var apiUrl = '/api/dis/login/register';
					var apiData = {
						name: name,
						username: username,
						code: code,
						js_code: res.code,
						image: allImg.store_header.id,
						area: that.data.region,
						school: schoolname,
					}
				}
			
				if (res.code) {
					util.fetchPost(apiUrl,apiData, function (res) {
						util.hideLoading();
						if (res.state == 1) {
							util.showSuccess('注册成功');
							wx.reLaunch({
								url: '../login/login',
							})
						} else {
							util.message(res.datas);
						}
					});
				} else {
					console.log('登录失败！' + res.errMsg)
				}
			}
		})



		

	},
	//进入协议详情
	detilxieyiTap: function (e) {
		wx.navigateTo({
			url: '../detils/detils',
			success: function (res) { },
			fail: function (res) { },
			complete: function (res) { },
		})
	},
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
	onReady: function () {

	},

    /**
     * 生命周期函数--监听页面显示
     */
	onShow: function () {

	},

    /**
     * 生命周期函数--监听页面隐藏
     */
	onHide: function () {

	},

    /**
     * 生命周期函数--监听页面卸载
     */
	onUnload: function () {

	},

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
	onPullDownRefresh: function () {

	},

    /**
     * 页面上拉触底事件的处理函数
     */
	onReachBottom: function () {

	},

    /**
     * 用户点击右上角分享
     */
	onShareAppMessage: function () {

	}
})